package com.kly.smartbi.manager;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.UUID;
import com.kly.smartbi.common.ErrorCode;
import com.kly.smartbi.config.CosClientConfig;
import com.kly.smartbi.exception.ThrowUtils;
import com.kly.smartbi.model.dto.post.UploadResult;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.persistence.CIObject;
import com.qcloud.cos.model.ciModel.persistence.OriginalInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

/**
 * 文件上传通用方法
 *
 * @author admin
 * @date 2025/4/8
 */
@Slf4j
@Component
public class FileManager {

    @Resource
    private CosManager cosManager;

    @Resource
    private CosClientConfig cosClientConfig;


    /**
     * 返回对象的 URL
     */
    public String getObjectUrl(String uploadPath) {
        // https://smart-bi-1329071127.cos.ap-chengdu.myqcloud.com/
        // public/2025/04/08/ec5bf0b6-4e86-4222-a974-11146e6d2c34.png
        return String.format("https://%s.cos.%s.myqcloud.com/%s",
                cosClientConfig.getBucket(),
                cosClientConfig.getRegion(),
                uploadPath);
    }

    /**
     * 上传文件
     * @param file
     * @param uploadPathPrefix
     * @return
     */
    public UploadResult uploadFile(MultipartFile file, String uploadPathPrefix) {
        ThrowUtils.throwIf(file.isEmpty(), ErrorCode.PARAMS_ERROR, "上传文件为空");
        // 创建临时文件
        String suffix = FileUtil.getSuffix(file.getOriginalFilename());
        File tempFile = null;
        // 设置上传路径 文件名称 + 日期 + uuid + suffix
        String date = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
        String uuid = UUID.randomUUID().toString();
        String uploadPath = String.format("%s/%s/%s.%s", uploadPathPrefix, date, uuid, suffix);
        try {
            tempFile = File.createTempFile("temp", String.format(".%s", suffix));
            // 保存到文件
            file.transferTo(tempFile);
            //      上传文件
            PutObjectResult putObjectResult = cosManager.putObject(uploadPath, tempFile);
            OriginalInfo originalInfo = putObjectResult.getCiUploadResult().getOriginalInfo();
            String originalKey = originalInfo.getKey();
            CIObject ciObject = putObjectResult.getCiUploadResult().getProcessResults().getObjectList().get(0);
            String compressKey = ciObject.getKey();
            UploadResult uploadResult = new UploadResult();
            uploadResult.setOriginalUrl(getObjectUrl(originalKey));
            uploadResult.setCompressUrl(getObjectUrl(compressKey));
            return uploadResult;
        } catch (IOException e) {
            log.error("创建临时文件失败", e);
            return null;
        } finally {
            // 删除临时文件
            if (tempFile != null) {
                tempFile.delete();
            }
        }
    }
}
